﻿import ko = require("knockout");

class ScrollTopHandler {
    static create() {
        ko.bindingHandlers.scrollProgress = {
            init: (element, valueAccessor) => {
                element.dataset.couldUpdateTimer = setTimeout(() => { }, 0);
                element.couldUpdate = true;

                element.addEventListener("scroll", (event) => {
                    valueAccessor()(element.scrollTop / (element.scrollHeight - element.clientHeight));

                    element.couldUpdate = false;
                    clearTimeout(element.couldUpdateTimer);
                    element.couldUpdateTimer = setTimeout(() => { element.couldUpdate = true }, 100);
                });
            },
            update: (element, valueAccessor) => {
                if (!element.couldUpdate) return;
                element.scrollTop = ko.unwrap(valueAccessor()) * (element.scrollHeight - element.clientHeight);
            }
        };
    }
}

export = ScrollTopHandler;